package com.tianlang.schedule;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.tianlang.cache.Cache;
import com.tianlang.domain.pojo.Authority;
import com.tianlang.domain.pojo.Role;
import com.tianlang.service.IBaseManager;
import com.tianlang.util.StringUtil;

/**
 * 
 * @author mcp
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class Schedule {

	private static final Logger log = Logger.getLogger(Schedule.class);

	@Autowired
	private IBaseManager baseManager;

	private boolean isRun = true;

	@Scheduled(fixedRate = 1000 * 60 * 60 * 24)
	public void scheduleRun() {
		if (isRun) {
			isRun = false;
			tokenInit();
			loadResourceDefine();
		}
	}

	/**
	 * 
	 */
	@Scheduled(cron = "0 0 * * * ?")
	public void tokenInit() {

	}

	/**
	 * 加载权限与角色 应当是资源为key， 权限为value。 资源通常为url， 权限就是那些以ROLE_为前缀的角色。
	 * 一个资源可以由多个权限来访问。MySecurityMetadataSource、自定义权限标签需要用到
	 */
	@SuppressWarnings("unchecked")
	private void loadResourceDefine() {
		List<Authority> authorities = baseManager.getObjects(Authority.class);
		for (Authority authority : authorities) {
			String url = authority.getName();
			List<Role> roles = authority.getRoles();
			Collection<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
			for (Role role : roles) {
				String auth = role.getTag();
				if (StringUtil.isNotEmpty(auth)) {
					ConfigAttribute attribute = new SecurityConfig("ROLE_" + auth);
					attributes.add(attribute);
				}
			}
			Cache.resourceMap.put(url, attributes);
		}
		log.info("加载权限与角色完成。。。。。。");
	}
}
